iT邦幫忙

2021 iThome 鐵人賽

DAY 28
0

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~


796. Rotate String

Question

Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.

A shift on s consists of moving the leftmost character of s to the rightmost position.

  • For example, if s = "abcde", then it will be "bcdea" after one shift.

Example

Example1

Input: s = "abcde", goal = "cdeab"
Output: true

Example2

Input: s = "abcde", goal = "abced"
Output: false

Constraints

  • 1 <= s.length, goal.length <= 100
  • s and goal consist of lowercase English letters.

解題

題目

首先先簡單的翻譯一下題目
給一個字串s跟目標字串goal,要判斷goal是不是可以透過位移s的字串來得到。

Think

作法大致上是這樣

  • s[index:]可以得到從index這個位置到s最後的所有字元,s[index]可以在得到從s的頭到index前的所有字元,把兩個加起來,就可以達到shift的效果。

Code

Python

class Solution:
    def rotateString(self, s: str, goal: str) -> bool:
        
        for index in range(len(s)):
            if (s[index:] + s[:index]) == goal:
                return True
            
        return False

Result

  • Python

大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 27 - Detect Capital
下一篇
Day 29 - Baseball Game
系列文
30天 Leetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言